package org.chw.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/* *
 * @ClassName ConsumerRest
 * @Author chen
 * @Description 服务消费者
 * @Date 2018/5/23 19:46
 * @Version 1.0
 **/
@RestController
public class ConsumerRest {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerRest.class);

    @RequestMapping(value = "/hello", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String sayHello() {
        return this.restTemplate.getForObject("http://first-producer/1", String.class);
    }

    @RequestMapping(value = "/service", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public void getServicesList() {
        //获取服务id
        List<String> serviceList = this.discoveryClient.getServices();
        for (String service : serviceList) {
            //获取服务实例
            List<ServiceInstance> serviceInstanceList = this.discoveryClient.getInstances(service);
            for (ServiceInstance serviceInstance : serviceInstanceList) {
                //打印实例信息
                LOGGER.info("serviceId:{},port:{},size:{}", serviceInstance.getServiceId(), serviceInstance.getPort(), serviceInstanceList.size());
            }
        }
    }
}
